<?php
namespace Home\Controller;

use Think\Controller;

class FileController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function upload()
  {
    $storage_config = D('apps')->storage_config($this->app_id);

    switch ($storage_config['storage_type']) {
      case 1:
        $upload_config = array(
          'host' => $storage_config['upyun_host'],
          'bucket' => $storage_config['upyun_bucket'],
          'username' => $storage_config['upyun_username'],
          'password' => $storage_config['upyun_password'],
          'endpoint' => $storage_config['upyun_endpoint']
        );
        $upload_type = 'Upyun';
        $domain = $storage_config['upyun_endpoint'];
        break;
      case 2:
        $upload_config = array(
          'AccessKeyId' => $storage_config['oss_key'],
          'AccessKeySecret' => $storage_config['oss_secret'],
          'domain' => $storage_config['oss_domain'],
          'Bucket' => $storage_config['oss_bucket'],
          'Endpoint' => $storage_config['oss_endpoint']
        );
        $upload_type = 'Aliyun';
        $domain = $storage_config['oss_domain'];
        break;
      case 3:
        $upload_config = array(
          'secretKey' => $storage_config['qiniu_secretkey'],
          'accessKey' => $storage_config['qiniu_accesskey'],
          'domain' => $storage_config['qiniu_domain'],
          'bucket' => $storage_config['qiniu_bucket'],
          'area' => $storage_config['qiniu_area']
        );
        $upload_type = 'Qiniu';
        $domain = $storage_config['qiniu_domain'];
        break;
    }
    //TODO
    $upload = new \Think\Upload(array(), $upload_type, $upload_config);
    

    $upload->rootPath = './';
    $month = date('Ym');
    $upload->savePath = "{$month}/";
    $upload->autoSub = false;
    $info = $upload->upload();

    if (!$info) {
      return_data("error", "upload.files.error", $upload->getError());
    } else {
      foreach ($info as $file) {
        $file_arr[] = "$domain/{$month}/$file[savename]";
      }
    }

    if ($info) {
      return_data("success", "upload.files.success", $file_arr);
    } else {
      return_data("error", "upload.files.error");
    }
  }
}
